package com.chaoyong.higo.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.content.Intent;
import android.provider.ContactsContract.CommonDataKinds.Relation;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chaoyong.higo.R;
import com.chaoyong.higo.adapter.ProtailAdapter;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.bean.ListEntity;
import com.chaoyong.higo.bean.ListEntity2;
import com.chaoyong.higo.bean.UserListBean;
import com.chaoyong.higo.cainiaowo.CartProvider;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.TransferTool;
import com.chaoyong.higo.utils.V;
import com.chaoyong.higo.utils.Values;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 2016.3.2
 * 
 * @author 丁晶
 * 商品详情
 */
public class ProductDeTimeActivity extends BaseActivity {
	@Override
	public int layoutResID() {
		return R.layout.activity_product_detime;
	}

	private Context context;
	private TextView title_center_text;
	private TextView title_right_text;
	private ImageView imageButton;
	private RecyclerView recyclerView;
	private ProtailAdapter adapter;
	private ImageView detail_shar;
	private ListEntity list;
	private TextView name_tx, left_tx, total_tx, count_tx, price_tx;
	private ProgressBar progressBar;
	private ImageView imagedet_imgbt;
	private ImageView icon_cart;
	private Button button1;
	
	private CartProvider cartProvider;
	
	private RelativeLayout imagedet_lay,imagedet_lay_order;

	private ImageView itemshop_image_img;
	private ListEntity entity;
	private ListEntity2 entity2;

	private String goodsId;
	private String goodsExpe;
	private String goodsInfo;
	
	private JSONObject detail;

	@Override
	public void findView() {
		title_center_text = (TextView) findViewById(R.id.title_center_text);
		title_right_text = (TextView) findViewById(R.id.title_right_text);
		imageButton = (ImageView) findViewById(R.id.itemshop_shop_imgbt);
		recyclerView = (RecyclerView) findViewById(R.id.prodetime_user_recycler);
		detail_shar = V.f(this, R.id.detail_shar);

		name_tx = V.f(this, R.id.prodet_name_tx);
		left_tx = V.f(this, R.id.prodet_left_tx);
		total_tx = V.f(this, R.id.prodet_total_tx);
		count_tx = V.f(this, R.id.prodet_count_tx);
		price_tx = V.f(this, R.id.prodet_price_tx);
		progressBar = V.f(this, R.id.test_progressbar);
		imagedet_imgbt = V.f(this, R.id.imagedet_imgbt);
		icon_cart = V.f(this, R.id.icon_cart);
		button1 = V.f(this, R.id.button1);

		itemshop_image_img = V.f(this, R.id.itemshop_image_img);

		imagedet_lay = V.f(this, R.id.imagedet_lay);
		imagedet_lay_order = V.f(this, R.id.imagedet_lay_order);
	}

	@Override
	public void init() {
		context = this;
		cartProvider = new CartProvider(context);
		list = (ListEntity) getIntent().getSerializableExtra("list");
		title_center_text.setText("商品详情");
		title_right_text.setText("第--期");
		title_right_text.setOnClickListener(this);

		// 看不懂啥意思，得，管你的，就照着你的写吧。
		entity = (ListEntity) getIntent().getSerializableExtra("listEntity");
		entity2 = (ListEntity2) getIntent().getSerializableExtra("listEntity2");
		setDatas(entity, entity2);
		recyclerView.setLayoutManager(new LinearLayoutManager(context));

		imagedet_imgbt.setOnClickListener(this);
		detail_shar.setOnClickListener(this);
		icon_cart.setOnClickListener(this);
		button1.setOnClickListener(this);
		
		imagedet_lay.setOnClickListener(this);
		imagedet_lay_order.setOnClickListener(this);
	}

	private void setDatas(ListEntity entity, ListEntity2 e2) {
		if (null != entity) {

			goodsExpe = entity.getExpect();
			goodsId = entity.getId();
			goodsInfo = entity.getGoods_info();
			//String uri = entity.getFace_img().get(0);
			String uri = entity.getCover_img();
			if(uri.contains("|")){
				//uri = uri.split("\\|")[0];
				ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri.split("\\|")[0], itemshop_image_img);
			}
			// 价格
			Double goods_price = entity.getGoods_price();
			price_tx.setText(goods_price + "");
			// 名称
			String goods_name = entity.getGoods_name();
			name_tx.setText("(第" + entity.getExpect() + context.getResources().getString(R.string.expect) + ")" + goods_name);
			// 总共
			String totals = TransferTool.getString(goods_price + "", ".");
			total_tx.setText(totals);
			// 已参与
			int count = entity.getSurplus();
			count_tx.setText(count + "");
			// 还剩
			int left = TransferTool.Strtoint(goods_price + "", ".") - count;
			left_tx.setText(left + "");
			Double d = (double) (count / (TransferTool.Strtoint(goods_price + "", ".") / 100.00));
			//Double d = (double) (count / Double.parseDouble(goods_price) / 100);
			if(d < 1 && d > 0){
				progressBar.setProgress(1);
			}else{
				progressBar.setProgress(d.intValue());
			}
			String except = entity.getExpect();

			title_right_text.setText("第" + except + "期");
			
			userlist(goodsId, goodsExpe);
		} else if (null != e2) {
			goodsExpe = e2.getExpect();
			goodsId = e2.getId();
			goodsInfo = e2.getGoods_info();
			String uri = e2.getCover_img().get(0);
			ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri, itemshop_image_img);
			// 价格
			String goods_price = e2.getGoods_price();
			price_tx.setText(goods_price);
			// 名称
			String goods_name = e2.getGoods_name();
			name_tx.setText("(第" + e2.getExpect() + context.getResources().getString(R.string.expect) + ")" + goods_name);
			// 总共
			String totals = TransferTool.getString(goods_price, ".");
			total_tx.setText(totals);
			// 已参与
			int count = e2.getSurplus();
			count_tx.setText(count + "");
			// 还剩
			int left = TransferTool.Strtoint(goods_price, ".") - count;
			left_tx.setText(left + "");
			Double d = (double) (count / (TransferTool.Strtoint(goods_price, ".") / 100.00));
			//Double d = (double) (count / Double.parseDouble(goods_price) / 100);
			//progressBar.setProgress(d.intValue());
			if(d < 1 && d > 0){
				progressBar.setProgress(1);
			}else{
				progressBar.setProgress(d.intValue());
			}
			String except = e2.getExpect();

			title_right_text.setText("第" + except + "期");
			
			userlist(goodsId, goodsExpe);
		}else{
			//这个是从夺宝记录跳过来的。
			goodsId = getIntent().getStringExtra("goods_id");
			JSONObject json = new JSONObject();
			JSONObject info = new JSONObject();
			try {
				info.put("goods_id", goodsId);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				json.put("path", "/M/Goods/goodsData");
				json.put("info", info);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			RequestParams params = new RequestParams();
			try {
				params.setBodyEntity(new StringEntity(json.toString(), "utf-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			HttpUtils utils = new HttpUtils();
			utils.send(HttpMethod.POST, OApi.appport_winningGoods, params, new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					// TODO Auto-generated method stub
					String result = arg0.result;
					try {
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("status") == 1){
							detail = jo.getJSONObject("data").getJSONObject("datail");
							
							goodsExpe = detail.getString("expect");
							goodsInfo = detail.getString("goods_info");
							
							String uri = detail.getString("cover_img");
							/*if(uri.contains("|")){
								//uri = uri.split("\\|")[0];
								ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri.split("\\|")[0], itemshop_image_img);
							}*/
							ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uri, itemshop_image_img);
							// 价格
							Double goods_price = detail.getDouble("goods_price");
							price_tx.setText(goods_price + "");
							// 名称
							String goods_name = detail.getString("goods_name");
							name_tx.setText("(第" + detail.getString("expect") + context.getResources().getString(R.string.expect) + ")" + goods_name);
							// 总共
							String totals = TransferTool.getString(goods_price + "", ".");
							total_tx.setText(totals);
							// 已参与
							int count = detail.getInt("has_num");
							count_tx.setText(count + "");
							// 还剩
							int left = TransferTool.Strtoint(goods_price + "", ".") - count;
							left_tx.setText(left + "");
							Double d = (double) (count / (TransferTool.Strtoint(goods_price + "", ".") / 100.00));
							//Double d = (double) (count / Double.parseDouble(goods_price) / 100);
							if(d < 1 && d > 0){
								progressBar.setProgress(1);
							}else{
								progressBar.setProgress(d.intValue());
							}
							String except = detail.getString("expect");

							title_right_text.setText("第" + except + "期");
							
							userlist(goodsId, goodsExpe);
							
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			});
		}
		
		
	}

	/*@Override
	protected void onStart() {
		super.onStart();
		userlist(goodsId, goodsExpe);
	}*/

	private void userlist(String goodsId, String goodsExpe) {
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object = new JSONObject();
		try {
			object.put("model", "GoodsRecord");
			object.put("function", "getRecord");
			object.put("app", "1");
			object.put("code", goodsId + "," + goodsExpe);
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// param.setBodyEntity(new StringEntity(jsonObject.toString(),
		// "UTF-8"));
		utils.send(HttpMethod.POST, Values.MAIN_RECOMMEND, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				if (result != null) {
					JSONObject object;
					try {
						object = new JSONObject(result);
						if (object.getString("status").equals("1")) {
							Gson gson = new GsonBuilder().create();
							UserListBean bean = gson.fromJson(result, UserListBean.class);
							adapter = new ProtailAdapter(context, bean.getData().getList());
							recyclerView.setAdapter(adapter);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_right_text:
			Intent i = new Intent(context, SeleCounActivity.class);
			i.putExtra("goods_id", entity.getId());
			startActivity(i);
			break;
		case R.id.imagedet_lay_order:
			startActivity(new Intent(context, SharActivity.class));
			break;
		case R.id.imagedet_lay:
			Intent intent = new Intent(context, ImagDetailActivity.class);
			intent.putExtra("info", goodsInfo);
			startActivity(intent);
			break;
		case R.id.icon_cart:
			if(entity != null){
				showToast("已添加到购物车");
				cartProvider.put(entity);
				if(!Values.idList.contains(entity.getGoods_id())){
					Values.idList.add(entity.getGoods_id());
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
				
			}else if(entity2 != null){
				showToast("已添加到购物车");
				ListEntity le = new ListEntity();
				le.setAuto_release(entity2.getAuto_release());
				le.setExpect(entity2.getExpect());
				le.setFace_img(entity2.getCover_img());
				le.setGoods_expect(entity2.getGoods_expect());
				le.setGoods_id(entity2.getGoods_id());
				le.setGoods_info(le.getGoods_info());
				le.setGoods_name(entity2.getGoods_name());
				le.setGoods_price(Double.parseDouble(entity2.getGoods_price()));
				le.setGoods_status(entity2.getGoods_status());
				le.setId(entity2.getId());
				le.setIs_down_line(entity2.getIs_down_line());
				le.setLimit_buy_num(entity2.getLimit_buy_num());
				le.setOpen_time(entity2.getOpen_time());
				le.setParent_id(entity2.getParent_id());
				le.setSurplus(entity2.getSurplus());
				le.setType_id(entity2.getType_id());
				cartProvider.put(le);
				if(!Values.idList.contains(entity2.getGoods_id())){
					Values.idList.add(entity2.getGoods_id());
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
			}else{
				showToast("已添加到购物车");
				ListEntity le = new ListEntity();
				try {
					le.setAuto_release(detail.getString("auto_release"));
					
					le.setExpect(detail.getString("expect"));
					List<String> img = new ArrayList<String>();
					String[] imgs = detail.getString("cover_img").split("\\|");
					for (int j = 0; j < imgs.length; j++) {
						img.add(imgs[j]);
					}
					le.setFace_img(img);
					le.setGoods_expect(detail.getString("goods_expect"));
					le.setGoods_id(goodsId);
					le.setGoods_info(detail.getString("goods_info"));
					le.setGoods_name(detail.getString("goods_name"));
					le.setGoods_price(Double.parseDouble(detail.getString("goods_price")));
					le.setGoods_status(detail.getString("status"));
					le.setId(goodsId);
					//le.setIs_down_line(detail.getString("auto_release"));
					le.setLimit_buy_num(detail.getString("limit_buy_num"));
					//le.setOpen_time(detail.getString("auto_release"));
					//le.setParent_id(detail.getString("auto_release"));
					le.setSurplus(detail.getInt("has_num"));
					le.setType_id(detail.getString("type_id"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//entity = le;
				cartProvider.put(le);
				if(!Values.idList.contains(goodsId)){
					Values.idList.add(goodsId);
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
			}
			break;
		case R.id.button1:
			if(entity != null){
				showToast("已添加到购物车，立即支付吧！");
			cartProvider.put(entity);
			if(!Values.idList.contains(entity.getGoods_id())){
				Values.idList.add(entity.getGoods_id());
				if (MainActivity.badgeView.isShown()) {
					MainActivity.badgeView.increment(1);
				} else {
					MainActivity.badgeView.show();
				}
			}
			}else if(entity2 != null){
				showToast("已添加到购物车，立即支付吧！");
				ListEntity le = new ListEntity();
				le.setAuto_release(entity2.getAuto_release());
				le.setExpect(entity2.getExpect());
				le.setFace_img(entity2.getCover_img());
				le.setGoods_expect(entity2.getGoods_expect());
				le.setGoods_id(entity2.getGoods_id());
				le.setGoods_info(le.getGoods_info());
				le.setGoods_name(entity2.getGoods_name());
				le.setGoods_price(Double.parseDouble(entity2.getGoods_price()));
				le.setGoods_status(entity2.getGoods_status());
				le.setId(entity2.getId());
				le.setIs_down_line(entity2.getIs_down_line());
				le.setLimit_buy_num(entity2.getLimit_buy_num());
				le.setOpen_time(entity2.getOpen_time());
				le.setParent_id(entity2.getParent_id());
				le.setSurplus(entity2.getSurplus());
				le.setType_id(entity2.getType_id());
				cartProvider.put(le);
				if(!Values.idList.contains(entity2.getGoods_id())){
					Values.idList.add(entity2.getGoods_id());
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
			}else{
				showToast("已添加到购物车，立即支付吧！");
				ListEntity le = new ListEntity();
				try {
					le.setAuto_release(detail.getString("auto_release"));
					
					le.setExpect(detail.getString("expect"));
					List<String> img = new ArrayList<String>();
					String[] imgs = detail.getString("cover_img").split("\\|");
					for (int j = 0; j < imgs.length; j++) {
						img.add(imgs[j]);
					}
					le.setFace_img(img);
					le.setGoods_expect(detail.getString("goods_expect"));
					le.setGoods_id(goodsId);
					le.setGoods_info(detail.getString("goods_info"));
					le.setGoods_name(detail.getString("goods_name"));
					le.setGoods_price(Double.parseDouble(detail.getString("goods_price")));
					le.setGoods_status(detail.getString("status"));
					le.setId(goodsId);
					//le.setIs_down_line(detail.getString("auto_release"));
					le.setLimit_buy_num(detail.getString("limit_buy_num"));
					//le.setOpen_time(detail.getString("auto_release"));
					//le.setParent_id(detail.getString("auto_release"));
					le.setSurplus(detail.getInt("has_num"));
					le.setType_id(detail.getString("type_id"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//entity = le;
				cartProvider.put(le);
				if(!Values.idList.contains(goodsId)){
					Values.idList.add(goodsId);
					if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}
				}
			}
			Intent in = new Intent(context, MainActivity.class);
			in.putExtra("tag", 3);
			startActivity(in);
			
			break;
		}
	}

}
